const express = require('express');
const fs = require('fs');
const pool = require('../pool.js');
const log = require('../log');
const path = require('path');

const router = express.Router();

const mdPath = path.resolve(__dirname, '../public/md');

// 文章列表路由
router.get('/list', (req, res) => {
	let obj = req.query;
	start = (obj.page - 1) * obj.limit;
	end = start + parseInt(obj.limit);
	sql = 'select id,title,description,pubtime,author from list limit ? , ?';
	pool.query(sql, [start, end], (err, data) => {
		res.send(data);
	});
});

// 文章详情路由
router.get('/details', (req, res) => {
	let obj = req.query;
	sql = 'select src from list where id = ?';
	pool.query(sql, obj.id, (err, data) => {
		let detailsPath = path.resolve(mdPath, data[0].src);
		res.sendFile(detailsPath);
	});
});

// 上传笔记路由
router.post('/upload', (req, res) => {
	let obj = req.body;
	sqlSearch = 'select * from list where title = ?';
	pool.query(sqlSearch, obj.title, (data) => {
		if (!data) {
			// fs.writeFileSync(`public\\md\\${obj.title}.md`, obj.md, (err) => {
			// 	console.log(err);
			// });
			fs.writeFileSync(`${mdPath}\\${obj.title}.md`, obj.md, (err) => {
				console.log(err);
			});
			sql = 'insert into list set ?';
			let object = {
				title: obj.title,
				description: obj.description,
				src: `${mdPath}/${obj.title}.md`,
				pubtime: new Date().getTime(),
				author: obj.uname,
			};
			pool.query(sql, object, (data) => {
				console.log(data);
			});
			res.send({ code: 202, msg: '上传成功' });
		} else {
			res.sned({ code: 302, msg: '文章已存在' });
		}
	});
});

module.exports = router;
